package ofmybatis.demo.bean;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class Components {
    @Resource
    private AutowireCapableBeanFactory beanFactory;

    private static Components instance;

    public Components(){
        instance = this;
    }

    public <T> T getComponent(Class<T> clz){
        return beanFactory.getBean(clz);
    }

    public Object getBean(String name){
        return beanFactory.getBean(name);
    }

    public void autowireBean(Object bean){
        beanFactory.autowireBean(bean);
    }

    public <T> T newInstance(Class<T> clz){
        try {
            T obj = clz.newInstance();
            beanFactory.autowireBean(obj);
            return obj;
        } catch (InstantiationException e) {
            throw new RuntimeException(clz+"对象初始化失败，对象应该包含无参构造方法", e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(clz+"对象初始化失败，此类不可为接口、主类型、抽象类", e);
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T newInstance(String type, Class<T> typeRequire){
        try {
            Class<?> clz = Class.forName(type);
            if (typeRequire.isAssignableFrom(clz)){
                T obj = (T) newInstance(clz);
                return obj;
            }else{
                throw new RuntimeException(type + "必须实现 " + typeRequire + "接口");
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(type+"对象不存在", e);
        }
    }

    public static Components getInstance(){
        return instance;
    }

    public void test () {
        System.out.println("Components.test()");
    }

}
